﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using Newtonsoft.Json;
using eCommerce.core.Helpers;
using eCommerce.db.BORespository;
using eCommerce.db.DataRespository;
using eCommerce.log;

namespace eCommerce.db.Action
{
    public class IeAction : IBaseAction
    {
        public void Do(HttpContext context)
        {
            var actionName = Utils.GetIdFromRequestString(Utils.Action, string.Empty);

            var responseData = new ResponseData();
            switch (actionName)
            {
                case "listsearch":
                    responseData = GetListSearch();
                    break;

                case "delete":
                    responseData = Delete();
                    break;

                case "readexcel":
                    responseData = ReadExcel();
                    break;
                case "executeexcel":
                    responseData = ExecuteExcel();
                    break;

                case "":
                    responseData.Success = false;
                    responseData.Message = "Can not found this action.";
                    break;
            }

            var jSonString = JsonConvert.SerializeObject(responseData, Utils.SerializeFormat("MM/dd/yyyy HH:mm:ss"));
            if (!string.IsNullOrEmpty(context.Request.Params["callback"]))
                jSonString = string.Format("{0}({1})", context.Request.Params["callback"], jSonString);
            context.Response.Write(jSonString);
        }

        public static ResponseData GetListSearch()
        {
            var responseData = new ResponseData();
            var type        = Utils.GetIdFromRequestString(Utils.TypeId, 0);
            var storeId     = Utils.GetIdFromRequestString(Utils.StoreId, 0);
            var keyword     = Utils.GetIdFromRequestString(Utils.Keyword, string.Empty);
            var pageIndex   = Utils.GetIdFromRequestString(Utils.PageIndex, 0);
            var pageSize    = Utils.GetIdFromRequestString(Utils.PageSize, 0);
            var startDate   = Utils.GetIdFromRequestString(Utils.StartDate, string.Empty);
            var endDate     = Utils.GetIdFromRequestString(Utils.EndDate, string.Empty);

            var totalRecords = 0;

            try
            {
                var lstIe = IeBo.Search(type, storeId, keyword, pageIndex, pageSize, startDate, endDate, ref totalRecords);
                for (int i = 0; i < lstIe.Count; i++)
                {
                    lstIe[i].ItemIndex       = Utils.CalcItemIndex(i, pageIndex, pageSize);
                    lstIe[i].FormatCreatedOn = Utils.FormatIn_HHMM_DDMMYYYY(lstIe[i].CreatedOn);
                    lstIe[i].Quantity        = Utils.FormatPrice(Utils.ToDecimal(IeBo.GetQuantityByIeId(Utils.ToInt32(lstIe[i].IeId))));
                }
                    
                responseData.Success = true;
                responseData.Data = lstIe;
            }
            catch (Exception ex)
            {
                responseData.Success = false;
                responseData.Message = ex.Message;
                Logger.WriteLog(Logger.LogType.Error, ex.Message);
            }

            return responseData;
        }

        private static ResponseData Delete()
        {
            var responseData = new ResponseData();

            var ieId        = Utils.GetIdFromRequestString(Utils.IeId, 0);

            try
            {
                IeBo.Delete(ieId);

                responseData.Success = true;
                responseData.Data = null;
                responseData.TotalRow = 0;
            }
            catch (Exception ex)
            {
                responseData.Success = false;
                responseData.Message = ex.Message;
                Logger.WriteLog(Logger.LogType.Error, ex.Message);
            }
            return responseData;
        }

        public static ResponseData ReadExcel()
        {
            var responseData = new ResponseData();
            var storeId      = Utils.GetIdFromRequestString(Utils.StoreId, 0);
            var typeId       = Utils.GetIdFromRequestString(Utils.TypeId, 0);
            var description  = Utils.GetIdFromRequestString(Utils.Description, string.Empty);
            var filePath     = Utils.GetIdFromRequestString(Utils.FilePath, string.Empty);

            if (filePath.Length > 0)
            {
                using (SpreadsheetDocument document = SpreadsheetDocument.Open(HttpContext.Current.Server.MapPath(filePath), true))
                {
                    var errorMessage = string.Empty;

                    try
                    {
                        Workbook workBook = document.WorkbookPart.Workbook;
                        IEnumerable<Sheet> workSheets = workBook.Descendants<Sheet>();
                        SharedStringTable sharedStrings = document.WorkbookPart.SharedStringTablePart.SharedStringTable;

                        string sheetName = workSheets.First(s => s.Name == @"Product").Id;

                        var productSheet = (WorksheetPart)document.WorkbookPart.GetPartById(sheetName);

                        List<IeEntity> lstIe = IeBo.GetDataImportExport(typeId, storeId, description, productSheet.Worksheet, sharedStrings, ref errorMessage);

                        if (errorMessage == string.Empty && lstIe.Count > 0)
                        {
                            responseData.Success = true;
                            responseData.Data    = lstIe;
                        }
                        else
                        {
                            responseData.Success = false;
                            responseData.Message = errorMessage;
                        }
                    }
                    catch (Exception ex)
                    {
                        responseData.Success = false;
                        responseData.Message = errorMessage;
                        Logger.WriteLog(Logger.LogType.Error, ex.Message);
                    }
                }
            }

            return responseData;
        }

        public static ResponseData ExecuteExcel()
        {
            var responseData = new ResponseData();
            var storeId      = Utils.GetIdFromRequestString(Utils.StoreId, 0);
            var typeId       = Utils.GetIdFromRequestString(Utils.TypeId, 0);
            var description  = Utils.GetIdFromRequestString(Utils.Description, string.Empty);
            var filePath     = Utils.GetIdFromRequestString(Utils.FilePath, string.Empty);

            if (filePath.Length > 0)
            {
                using (SpreadsheetDocument document = SpreadsheetDocument.Open(HttpContext.Current.Server.MapPath(filePath), true))
                {
                    var errorMessage = string.Empty;

                    try
                    {
                        Workbook workBook = document.WorkbookPart.Workbook;
                        IEnumerable<Sheet> workSheets = workBook.Descendants<Sheet>();
                        SharedStringTable sharedStrings = document.WorkbookPart.SharedStringTablePart.SharedStringTable;

                        string sheetName = workSheets.First(s => s.Name == @"Product").Id;

                        var productSheet = (WorksheetPart)document.WorkbookPart.GetPartById(sheetName);

                        List<IeEntity> lstIe = IeBo.ExecuteImportExport(typeId, storeId, description, productSheet.Worksheet, sharedStrings, ref errorMessage);

                        if (errorMessage == string.Empty && lstIe.Count > 0)
                        {
                            responseData.Success = true;
                            responseData.Data = lstIe.Count;
                            responseData.Message = string.Format("{0} bản ghi đã được lưu vào db thành công!", lstIe.Count);                        
                        }
                        else
                        {
                            responseData.Success = false;
                            responseData.Message = errorMessage;
                        }
                    }
                    catch (Exception ex)
                    {
                        responseData.Success = false;
                        responseData.Message = errorMessage;
                        Logger.WriteLog(Logger.LogType.Error, ex.Message);
                    }
                }
            }

            return responseData;
        }

    }
}
